/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.chenweihuacwh.dao.baseData;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.chenweihuacwh.dto.baseData.User;

public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
	
	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		return getHibernateTemplate().find("from User");
	}
	
	public User saveUser(User user) {
		getHibernateTemplate().saveOrUpdate(user);
		return user;
	}
	
	public void removeUser(int id) {
		Object o = getHibernateTemplate().load(User.class, id);
		getHibernateTemplate().delete(o);
	}
	
	public User getUser(int id) {
		return (User)getHibernateTemplate().get(User.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public User getLoginUser(User user) {
		final String queryString = "from User u where u.userName='"
			+ user.getUserName() + "' and u.password='" + user.getPassword() + "'";
		List result = getHibernateTemplate().find(queryString);
		if (result == null || result.size() == 0) {
			return null;
		}
		return (User)result.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public long getUserByName(String userName) {
		final String queryString = "select count(id) from User u where u.userName='" + userName + "'";
		List result = getHibernateTemplate().find(queryString);
		if (result == null || result.size() == 0) {
			return 0;
		}
		if (result.get(0) == null) {
			return 0;
		}
		return (Long)result.get(0);
	}
}
